<template>
	<div>
		<div class="main_header">
			<div style="display: flex">
				<div style="margin-left: 30px; font-size: 1.275rem">
					试卷名：{{textname}}
				</div>
				<div style="margin-left: 30px; font-size: 1.275rem">
					<!-- 满分：<span style="color: red">{{question.testPaper.testPaperScore}}分</span> -->
				</div>
			</div>
			<div style="margin-left: 30px; font-size: 1.275rem; margin-right: 1.875rem">
				<el-button type="primary" round style="background-color: #03d3bd; border: none" @click="SubmitItem()">交卷</el-button>
			</div>
		</div>
		<div class="exam">
			<div class="title" style="position: relative">
				<div>
					<p style="font-size: 1.1875rem">监控区</p>
				</div>
				<div style="width: 100%" id="videobox">
					<video ref="video" id="video" autoplay=""></video>
					<canvas ref="canvas" id="canvas"></canvas>
				</div>
				<div>
					<p style="font-size: 1.1875rem">答题卡</p>
				</div>
				<div>
					<span v-for="(item, idx) in questions" :key="idx" @click="pages(idx)" style="margin-top: 10px" :class="{active:item.button}">
						{{ idx+1 }}</span>
					<!-- <span style="background-color: #03d3bd; margin-top: 10px">5</span> -->
				</div>
				<div class="Bottom" style="text-align: center">
					<span style="
              width: 20px;
              height: 20px;
              background-color: #03d3bd;
              margin-left: 0.625rem;
            "></span>
					已答
					<span style="width: 20px; height: 20px; margin-left: 0.625rem"></span>
					未答
					<!-- <span style="width: 30px;height: 30px;margin-left: 0.625rem;background-color: #ffaa00;"></span>
					收藏 -->
				</div>
			</div>
			<div class="topic">
				<div class="topic_main">
					<div>题目</div>
					<div>共2题</div>
				</div>

				<div class="question" v-for="(item, idx) in questions" :key="idx">

					<div style="display: flex;">{{ `${idx+1}.[${item.name}](${item.score})`}}
						<div v-html="`${md(item.content)}`"></div>
					</div>
					<div v-for="(Item,indx) in item.optionsList" :key="indx+'hh'" style="display: flex;">
						<div v-if="item.topicId==1">
							<el-radio v-model="item.answer" :label="Item.id" style="margin-top: 0.625rem;" @change="ChangeItem(idx)">
								<div style="display: flex;">{{letter[indx]}}:
									<div v-html="`${md(Item.content)}`"></div>
								</div>
							</el-radio>
						</div>
						<div v-if="item.topicId==2">
							<el-checkbox-group v-model="item.answerList">
								<el-checkbox :label="Item.id" :key="indx" @change="ChangeItem(idx)" style="margin-top: 1.25rem;">
									<div v-html="`${md(Item.content)}`"></div>
								</el-checkbox>
							</el-checkbox-group>
						</div>
					</div>
					<div v-if="item.topicId==3">

						<div v-for="(Item,indx) in exam" :key="indx+'hh'" style="display: flex;">
							<el-radio v-model="item.answer" :label="Item.id" style="margin-top: 0.625rem;" @change="ChangeItem(idx)">
								<div>{{letter[indx]}}:{{Item.value}}
								</div>
							</el-radio>
						</div>
					</div>
					<div v-if="item.topicId==4" style="height: 22.5rem;">
						<quill-editor v-model="item.answer" style="height:260px;background-color: white;margin-top: 1.25rem;"></quill-editor>
					</div>
					<div v-if="item.topicId==5" style="height: 22.5rem;">
						<quill-editor v-model="item.answer" style="height:260px;background-color: white;margin-top: 1.25rem;"></quill-editor>
					</div>


				</div>
			</div>
			<div class="left">
				<div>考试时间</div>
				<div style="color: red">0.0</div>
				<hr style="margin-top: 40px" color="#ececec" size="1" />
				<!-- <div>筛选试题</div>
				<el-dropdown style="width: 100%">
					<span class="el-dropdown-link">
						全部<i class="el-icon-arrow-down el-icon--right"></i>
					</span>
					<el-dropdown-menu slot="dropdown" style="width: 6%">
						<el-dropdown-item>已答</el-dropdown-item>
						<el-dropdown-item>未答</el-dropdown-item>
					</el-dropdown-menu>
				</el-dropdown> -->
			</div>
		</div>
		<!-- 隐藏input自动获取焦点 -->
		<input type="hidden" autofocus="true" />
	</div>
</template>

<script>
	import moment from "moment";
	import base64ToBlob from "base64ToBlob";
	import axios from "axios";
	import marked from "marked";
	import {
		TestManager
	} from "../../request/test.js"
	export default {
		data() {
			return {
				texts: ["简单", "一般", "困难"],
				js: "",
				star: false,
				isShow: true,
				page: 1,
				exam: [{
						value: "正确",
						id: 1
					},
					{
						value: "错误",
						id: 0
					}
				],
				timer: "",
				video: "",
				videowidth: 0,
				videoheight: 0,
				canvas: "",
				context: "",
				allowNum: 3,
				testid: "",
				question: [],
				questions: [],
				textname: '',
				answer: [],
				letter: ["A", "B", "C", "D", "E", "F", "G", "H", "R", "J", "K", "L"],
				data: []
			};
		},
		created() {
			this.testid = localStorage.getItem("Test");
			this.testid = JSON.parse(this.testid);
			this.getQuestionnaireTest();
			this.exam.num = [];
			// const allowNum =  localStorage.getItem('allowNum') 
			// if(parseInt(allowNum)>1){
			//   that.allowNum = parseInt(allowNum);
			// }
			// 记录切屏的次数
			const that = this;
			window.onblur = function() {
				console.log(that.$route);
				if (that.$route.name === "examination") {
					if (that.allowNum > 1) {
						that.$confirm('提交试卷')
							.then(_ => {
								that.allowNum--;
								// localStorage.setItem('allowNum', that.allowNum);
								// 交卷
								done()
							})
							.catch(_ => {
								// 计数一次
								that.allowNum--;
								that.recordAbnormal();
							});
					} else {
						that.recordAbnormal();
						// that.$alert("您已切屏，超过三次自动提交试卷");
					}
				}
			};
			history.pushState(null, null, document.URL);
			window.addEventListener('popstate', function() {
				history.pushState(null, null, document.URL);
			});
		},
		mounted() {
			const that = this;
			// var video = this.$refs.video;
			const video = document.getElementById("video");
			//访问摄像头
			if (
				navigator.mediaDevices.getUserMedia ||
				navigator.getUserMedia ||
				navigator.webkitGetUserMedia ||
				navigator.mozGetUserMedia
			) {
				//调用用户媒体设备, 访问摄像头
				getUserMedia({
					video: {
						width: 330,
						height: 212
					}
				}, success, error);
			} else {
				alert("不支持访问摄像头");
			}

			//访问用户媒体设备的兼容方法
			function getUserMedia(constraints, success, error) {
				if (navigator.mediaDevices.getUserMedia) {
					//最新的标准API
					navigator.mediaDevices
						.getUserMedia(constraints)
						.then(success)
						.catch(error);
				} else if (navigator.webkitGetUserMedia) {
					//webkit核心浏览器
					navigator.webkitGetUserMedia(constraints, success, error);
				} else if (navigator.mozGetUserMedia) {
					//firfox浏览器
					navigator.mozGetUserMedia(constraints, success, error);
				} else if (navigator.getUserMedia) {
					//旧版API
					navigator.getUserMedia(constraints, success, error);
				}
			}

			//成功回调
			function success(stream) {
				//兼容webkit核心浏览器
				const CompatibleURL = window.URL || window.webkitURL;
				video.srcObject = stream;
				video.play();
				that.video = video; // 保存video
				video.addEventListener("canplay", function() {
					that.videowidth = this.clientWidth;
					that.videoheight = this.clientHeight;
					that.canvas = document.getElementById("canvas");
					that.canvas.setAttribute("width", that.videowidth);
					that.canvas.setAttribute("height", that.videoheight);
					that.context = that.canvas.getContext("2d");
					// 调用定时器  5s 拍照一次
					that.timer = setInterval(() => {
						that.upload(); // 截屏并上传
					}, 10000);
				});
			}

			//失败回调
			function error(error) {
				console.log(error);
				console.log("访问用户媒体设备失败");
			}
		},
		methods: {
			SubmitItem() {
				var singleList = [];
				var multipleList = [];
				var judgeList = [];
				var fillsList = [];
				var shortAnswer = [];
				let data = [];
				for (let i = 0; i < this.questions.length; i++) {
					// alert(this.danxuanti[i].id);
					if (this.questions[i].topicId !== 2) {
						singleList.push({
							questionId: this.questions[i].id,
							questionAnswer: this.questions[i].answer
						});

					} else if (this.questions[i].topicId === 2) {
						multipleList.push({
							questionId: this.questions[i].id,
							questionAnswer: this.questions[i].answerList.join(',')
						});
					}
				}
				data.push(...singleList);
				data.push(...multipleList);
				data.push(...judgeList);
				data.push(...fillsList);
				data.push(...shortAnswer);
				TestManager.studentSubmitExam(data, 480, this.testid.id).then(res => {
					console.log(res);
					if (res.data.code == 500) {
						this.$message({
							message: res.data.message,
							type: 'warning'
						});
					} else {
						this.$message({
							message: '提交成功',
							type: 'success'
						});
						this.$router.push('/teststu');
						localStorage.removeItem("Test");
					}


				})
			},
			md(content) {
				return marked(content);
			},
			ChangeItem(id) {
				this.questions[id].button = true
				// this.$set(this.questions[id], 'button', true);
				// console.log(this.questions[id])
			},
			upload() {
				//   const that = this;
				//将视频写入canvas
				this.context.drawImage(
					this.video,
					0,
					0,
					this.videowidth,
					this.videoheight
				);
				//将Canvas的数据转换为base64位编码的PNG图像
				const imageData = this.canvas.toDataURL("image/png");
				//截取22位以后的字符串作为图像数据
				const imgStr = imageData.substr(22);
				const examId = this.testid.id; // 最终通过传参带过来
				const formdata = new FormData();
				const cutTime = moment().format("YYYY-MM-DD HH:mm:ss");
				formdata.append("cutTime", cutTime);
				formdata.append("examId", examId);
				// 将base64 转为 blob
				const faceFile = base64ToBlob(imgStr, "image/png");
				formdata.append("faceFile", faceFile);
				axios
					.post("http://101.43.71.61:8080/monitor/examUploadFace", formdata, {
						Headers: {
							token: localStorage.getItem("token"),
						},
					})
					.then((res) => {
						console.log(res);
					});
			},
			recordAbnormal() {
				if (this.allowNum >= 1) {
					var parmas = {
						findTime: moment().format("YYYY-MM-DD HH:mm:ss"),
						examId: this.testid.id,
						abnormalDescribe: "你一切屏3次以上"
					}
				} else {
					var parmas = {
						findTime: moment().format("YYYY-MM-DD HH:mm:ss"),
						examId: this.testid,
						abnormalDescribe: "你一切屏" + (3 - this.allowNum) + "次"
					}
				}

				axios
					.post("http://101.43.71.61:8080/monitor/recordAbnormal", this.qs.stringify(parmas), {
						Headers: {
							token: localStorage.getItem("token"),
						},
					})
					.then((res) => {
						console.log(res);
					});
			},
			getQuestionnaireTest() {
				var parmas = {
					id: this.testid.testPaperId
				}
				TestManager.getQuestionnaireTest(this.qs.stringify(parmas)).then(e => {
					console.log(e);
					this.question = e.data.data;
					this.textname = this.question.testPaper.name;
					this.questions = e.data.data.questions.map(q => {
						return {
							...q,
							answerList: [],
						}
					})
					console.log(this.questions);
				})
			},
			pages(id) {
				document.getElementsByClassName("question")[id].scrollIntoView();
			},

		},
		deactivated() {

			clearInterval(this.timer);
		}

	};
</script>

<style scoped>
	.topic_main {
		display: flex;
		justify-content: space-between;
	}

	.main_header {
		height: 5.5rem;
		/* margin-left: 2.25rem; */
		color: black;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: white;
		/* background-color: #03d3bd; */
	}

	.exam {
		width: 100vw;
		height: 100vh;
		background-color: #eff3f7;
		display: flex;
		justify-content: center;
	}

	.exam .title,
	.exam .left {
		margin: 50px 20px;
		height: 80%;
		background-color: #fff;
	}

	.exam .left {
		height: 30%;
	}

	.exam .topic {
		margin-top: 3.125rem;
		height: 80%;
		background-color: #fff;
	}

	.title {
		width: 15%;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20px;
	}

	.title div {
		width: 100%;
		border-bottom: 1px solid #ebebeb;
		margin-bottom: 20px;
		padding-bottom: 10px;
		display: flex;
		flex-wrap: wrap;
	}

	.title div:nth-child(2) {
		display: flex;
		flex-direction: column;
	}

	.title div p {
		display: block;
	}

	.title div>span {
		display: block;
		background-color: #e2e2e2;
		color: #ffffff;
		width: 30px;
		height: 30px;
		margin-right: 10px;
		text-align: center;
		line-height: 30px;
		border-radius: 5px;
		cursor: pointer;
	}

	.exam .topic {
		overflow: scroll;
		scrollbar-width: none;
	}

	.exam .topic::-webkit-scrollbar {
		width: 0;
	}

	.title {
		width: 15%;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20px;
	}

	.topic {
		width: 65%;
		padding: 20px;
		display: flex;
		flex-direction: column;
		position: relative;
	}

	.topic>span {
		display: block;
		height: 40px;
		line-height: 40px;
		font-weight: 500;
		font-size: 25px;
	}

	.topic .question {
		flex: 5;
		display: flex;
		flex-direction: column;
		padding: 50px;
		border-bottom: 1px solid #dfdfdf;
	}

	.topic .question .el-radio-group {
		display: flex;
		flex-direction: column;
	}

	.el-radio-group .el-radio {
		height: 40px;
		line-height: 40px;
	}

	.question li {
		list-style: none;
		display: block;
		height: 40px;
		margin-left: 1.875rem;
		display: flex;
		align-items: center;
	}

	.question span {
		display: inline-block;
		height: 20px;
		padding: 2px 5px;
		border-radius: 3px;
		border: 1px solid #fdf6ec;
	}

	.question .yes {
		background: #f0f9eb;
		color: #97d3bf;
	}

	.question .no {
		background-color: #fdf6ec;
		color: #e7ac95;
	}

	.left {
		margin-top: 3.25rem;
		background-color: #ffffff;
		width: 100px;
		text-align: center;
	}

	.left div {
		margin-top: 0.875rem;
	}

	.Bottom {
		position: absolute;
		bottom: 0;
		overflow: hidden;
		display: flex;
	}

	#videobox {
		flex-shrink: 0;
	}

	#video {
		width: 100%;
	}

	#canvas {
		position: absolute;
		z-index: -1;
	}

	.title .active {
		background-color: #03d3bd;
		margin-top: 10px
	}

	.el-radio {
		display: flex;
		margin-top: 0.625rem;
	}
</style>
